package com.macrounion.atv.service.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.macrounion.atv.service.entity.CurrentData;
import com.macrounion.atv.service.entity.ext.CurrentDataExt;
import com.macrounion.atv.service.mapper.CurrentDataMapper;
import com.macrounion.atv.service.mapper.CurrentDataMapperExt;
import com.macrounion.atv.service.service.CurrentDataService;
import com.macrounion.base.service.service.impl.BaseServiceImpl;
import com.macrounion.base.service.utils.DateUtils;

@Service
public class CurrentDataServiceImpl extends BaseServiceImpl<CurrentDataMapper, CurrentData> implements CurrentDataService {

	@Autowired
	private CurrentDataMapperExt currentDataMapperExt;
	
	@Override
	@Transactional
	public synchronized void saveData(List<CurrentData> datas) {
		if(CollectionUtils.isEmpty(datas))
    		return;
		//超时不用更新
		if(DateUtils.addSecond(datas.get(0).getCreatedTime(), 120).before(new Date()))
			return;
    	if(datas.size() > 100) {
    		saveToDatabase(datas.subList(0, 50));
    		saveData(datas.subList(50, datas.size()));
    	}else
    		saveToDatabase(datas);
	}
	
	private  void saveToDatabase(List<CurrentData> datas) {
//		System.out.println("开始------》"+Thread.currentThread().getId());
		currentDataMapperExt.saveData(datas);
//		System.out.println("结束------》"+Thread.currentThread().getId());
	}
	
	@Override
	public List<CurrentData> getCurrentData(String deviceId) {
		return currentDataMapperExt.getByDeviceId(deviceId);
	}

    @Override
    public List<CurrentData> getCurrentDataByDeviceCode(String deviceCode) {
        return currentDataMapperExt.getByDeviceCode(deviceCode);
    }
    
    @Override
    public Page<CurrentDataExt> requestPageExt(CurrentDataExt request) {
        if (request != null && request.getPageInfo() != null) {
            PageHelper.startPage(request.getPageInfo().getPageIndex(), request.getPageInfo().getPageSize());
            return (Page) currentDataMapperExt.requestPageExt(request);
        } else {
            return null;
        }
    }

    @Override
    public CurrentData getCurrentData(String deviceCode, String channelCode) {
        return currentDataMapperExt.getCurrentData(deviceCode, channelCode);
    }

    @Override
    public List<CurrentData> getSnmpTraps() {
        return currentDataMapperExt.getSnmpTraps();
    }

	@Override
	public int getTrapNum() {
		return currentDataMapperExt.getTrapNum();
	}
}